﻿using System;
using System.Text;
using Lawn.SocketClient.ProtoBase;

namespace Demo
{


    public class ResponsePackageInfo : IPackageInfo<byte>
    {
        public byte Key { get; set; }
        
        public byte[] Body { get; set; }
    }

    public class ResponseFilter : FixedHeaderReceiveFilter<ResponsePackageInfo>
    {
        
        //key + error|sucess +len 
        public ResponseFilter() : base(4)
        {
        }
        protected override int GetBodyLengthFromHeader(IBufferStream bufferStream, int length)
        {

           return  bufferStream.Skip(2).ReadInt16(false);
        }
        public override ResponsePackageInfo ResolvePackage(IBufferStream bufferStream)
        {

            var key = bufferStream.ReadByte();
            bufferStream.ReadByte();
            var len_b = bufferStream.ReadInt16(false);
            var body = new byte[len_b];
            bufferStream.Skip(1).Read(body, 0, len_b);

            return new ResponsePackageInfo()
            {
                Key = (byte)key,
                Body = body
            };

        }

      
    }

    class MyBeginEndMarkReceiveFilter : BeginEndMarkReceiveFilter<StringPackageInfo>
    {
        public MyBeginEndMarkReceiveFilter(string begin,string end)
            : base(Encoding.UTF8.GetBytes(begin), Encoding.UTF8.GetBytes(end))
        {
            this.begin = begin;
            this.end = end;
        }
        string begin;
        string end;
        public override StringPackageInfo ResolvePackage(IBufferStream bufferStream)
        {
            //获取接收到的完整数据，包括头和尾
            var body = bufferStream.ReadString((int)bufferStream.Length, Encoding.ASCII);
            //掐头去尾，只返回中间的数据
            body = body.Remove(body.Length - end.Length, end.Length);
            body = body.Remove(0, begin.Length);
            return new StringPackageInfo("", body, new string[] { });
        }
    }
}